import math
import os
import xml.dom.minidom
import cv2
import utils
import numpy as np


def ReplacePicAndLabel(XmlNameWithPath, OldLabelName, NewLabelName, TargetPicPath, PaddingRate, PaddingConstant, OutputPath):
    LabelInfos = utils.ReadXml(XmlNameWithPath)
    XmlName = XmlNameWithPath.split("\\")[-1]
    NewInfo = [OutputPath + "\\" + XmlName]
    img = MyImgRead(XmlNameWithPath[:-3] + "jpg")
    TargetPic = MyImgRead(TargetPicPath)

    # TargetPic = cv2.resize(TargetPic, (252, 300))
    # cv2.imshow("TargetPic", TargetPic)
    # cv2.waitKey(1)
    # yuv = cv2.cvtColor(TargetPic, cv2.COLOR_BGR2YUV)
    # cv2.imshow("yuv", yuv)
    # cv2.waitKey(1)
    # yuv[:, :, 0] = yuv[:, :, 0] / 2
    # cv2.imshow("yuv2", yuv)
    # cv2.waitKey(1)
    # rgb = cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR)
    # cv2.imshow("rgb", rgb)
    # cv2.waitKey(1)

    for LabelInfo in LabelInfos:
        if LabelInfo[-1] == OldLabelName:
            xmin = LabelInfo[0]
            ymin = LabelInfo[1]
            xmax = LabelInfo[2]
            ymax = LabelInfo[3]
            TargetPic = cv2.resize(TargetPic, (xmax - xmin, ymax - ymin))
            TargetPic = utils.BrightnessAverage(img, TargetPic)
            img[ymin:ymax, xmin:xmax] = TargetPic
            LabelInfo[0] = xmin - int(PaddingRate * (xmax - xmin) - PaddingConstant)
            LabelInfo[1] = ymin - int(PaddingRate * (ymax - ymin) - PaddingConstant)
            LabelInfo[2] = xmax + int(PaddingRate * (xmax - xmin) + PaddingConstant)
            LabelInfo[3] = ymax + int(PaddingRate * (ymax - ymin) + PaddingConstant)
            LabelInfo[4] = NewLabelName
        NewInfo.append(LabelInfo)
    cv2.imwrite(OutputPath + "\\" + XmlName[:-3] + 'jpg', img)
    utils.WriteXml(NewInfo, img.shape[1], img.shape[0])


def MyImgRead(ImgPath):
    ImgData = np.fromfile(ImgPath, np.uint8)
    Img = cv2.imdecode(ImgData, -1)
    return Img


SrcDir = r"F:\403\干活\6"
DstDir = r"F:\403\ImgOutput\ReplaceLabel2"
OldLabel = "nolimit"
NewLabel = "AmericaLimit60"
TargetPicPath = r"F:\403\ImgOutput\LabelOnly\00129_113_93_60.jpg"
PaddingRate = 0.1
PaddingConstant = 2

for root, dirs, files in os.walk(SrcDir):
    for file in files:
        if file[-1] == 'l':
            ReplacePicAndLabel(root + "\\" + file, OldLabel, NewLabel, TargetPicPath, PaddingRate, PaddingConstant, DstDir)
            print("%s\t转换完成" % file)
# xmlpath = r"F:\403\jpg\00001.xml"
# targetpic = r"F:\403\ImgOutput\AmericaSpeedLimit\限速标牌素材（标准）\美国标准标牌\95.jpg"
# ReplacePicAndLabel(xmlpath, "limit", "AmericaLimit", targetpic, 0.1, DstDir)
